package org.cloud.scheduler.model;

import java.lang.reflect.Method;

import org.apache.commons.lang.StringUtils;
import org.cloud.common.util.SpringContextUtils;
import org.cloud.module.common.constant.AdminConstants;
import org.cloud.module.common.entity.ScheduleJobEntity;
import org.cloud.module.common.entity.ScheduleJobLogEntity;
import org.cloud.scheduler.constant.ScheduleConstants;
import org.cloud.scheduler.service.ScheduleJobLogService;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.QuartzJobBean;


/**
 * 定时任务
 * @author wangyuan
 * @since 2019年6月15日 下午10:07:49
 *
 */
public class ScheduleJob extends QuartzJobBean {
	private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        ScheduleJobEntity scheduleJob = (ScheduleJobEntity) context.getMergedJobDataMap()
        		.get(ScheduleConstants.JOB_PARAM_KEY);
        
        //获取spring bean
        ScheduleJobLogService scheduleJobLogService = (ScheduleJobLogService) SpringContextUtils.getBean("scheduleJobLogService");
        
        //数据库保存执行记录
        ScheduleJobLogEntity log = new ScheduleJobLogEntity();
        log.setJobId(scheduleJob.getId());
        log.setBeanName(scheduleJob.getBeanName());
        log.setJobParams(scheduleJob.getJobParams());
        log.setCreatedUser(AdminConstants.USER_SYSTEM);
        log.setUpdatedUser(AdminConstants.USER_SYSTEM);
        
        //任务开始时间
        long startTime = System.currentTimeMillis();
        
        try {
            //执行任务
        	logger.debug("任务准备执行，任务ID：" + scheduleJob.getId());

			Object target = SpringContextUtils.getBean(scheduleJob.getBeanName());
			Method method = target.getClass().getDeclaredMethod("run", String.class);
			method.invoke(target, scheduleJob.getJobParams());
			
			//任务执行总时长
			long jobExecTime = System.currentTimeMillis() - startTime;
			log.setJobExecTime((int) jobExecTime);
			//任务状态    0：成功    1：失败
			log.setJobStatus(0);
			
			logger.debug("任务执行完毕，任务ID：" + scheduleJob.getId() + "  总共耗时：" + jobExecTime + "毫秒");
		} catch (Exception e) {
			logger.error("任务执行失败，任务ID：" + scheduleJob.getId(), e);
			
			//任务执行总时长
			long jobExecTime = System.currentTimeMillis() - startTime;
			log.setJobExecTime((int) jobExecTime);
			
			//任务状态    0：成功    1：失败
			log.setJobStatus(1);
			log.setErrorMsg(StringUtils.substring(e.toString(), 0, 2000));
		}finally {
			scheduleJobLogService.save(log);
		}
    }
}
